import json
import time
from datetime import datetime
from threading import Thread

import websocket

from .AIAgent import AIAgentByOpenAI
from ._dto import AgentUsePlate

from apps.nixia_public_institution_civil_service_examination.PublicInstitutionCivilServiceExamination import \
    PublicInstitutionCivilServiceExamination

from apps.daliy_news_collect.DailyNewsCollect import DailyNewsCollect


class WebSocketClient:
    def __init__(self, url, received_callback):
        if received_callback is None:
            received_callback = self.on_message

        self.ws = websocket.WebSocketApp(
            url,
            on_open=self.on_open,
            on_message=received_callback,
            on_error=self.on_error,
            on_close=self.on_close
        )

    def on_open(self, ws):
        print("WebSocket 已连接")

    def on_message(self, ws, message):
        print("收到消息:", message)
        try:
            # 将消息解析为 JSON 格式
            data = json.loads(message)
            print("收到消息:", data)

            # 根据消息类型进行处理
            if data.get("post_type") == "message":
                message_type = data.get("message_type")
                user_id = data.get("user_id")
                content = data.get("message")
                print(f"新消息 - 类型: {message_type}, 用户ID: {user_id}, 内容: {content}")
        except Exception as e:
            print("解析消息失败:", e)

    def on_error(self, ws, error):
        print("WebSocket 错误:", error)

    def on_close(self, ws, close_status_code, close_msg):
        print("WebSocket 连接已关闭")

    def start(self):
        self.ws.run_forever()


class XiaoYuQQBot:
    def __init__(
            self,
            ws_url: str,
            agent_use_plate: AgentUsePlate(),
            api_key: str,
            use_model: str
    ):
        self._AI_AGENT = AIAgentByOpenAI(
            agent_use_plate=agent_use_plate,
            api_key=api_key,
            use_model=use_model
        )

        apps_thread = Thread(target=self._apps_thread, daemon=True, args=(10,))
        apps_thread.start()

        self._ws_client = WebSocketClient(ws_url, self.on_message)
        self._ws_client.start()

    def _apps_thread(self, hour):
        has_send = False
        while True:
            date_time = datetime.now()
            if date_time.hour == hour and has_send is False:
                news_content = DailyNewsCollect().get_news_content()
                send_message = f"今日新闻：\n{news_content}"
                self.send_group_msg(target_group_id=1016660202,message=send_message)
                has_send = True
            else:
                time.sleep(3600)
                has_send = False

    def _send_switch(self, data):
        message_type = data.get("message_type")
        if message_type == "group":
            send = self.send_group_msg
            target_id = data.get("group_id")

        elif message_type == "private":
            send = self.send_message
            target_id = data.get("user_id")
        else:
            raise '出现其他的message_type'
        return send, target_id

    def _process_apps_content(self, message):
        try:
            print(message)
            worker_id = message.split('@')[-1]
            return_message = PublicInstitutionCivilServiceExamination().get_worker_info(worker_id)
            print(return_message)
        except Exception as e:
            print(e)
            return_message = '请发送  报考宁夏事业编@【岗位id】'
        return return_message

    def _message_event_process(self, data):
        message_type = data.get("message_type")
        user_id = data.get("user_id")
        content = data.get("message")
        print(f"新消息 - 类型: {message_type}, 用户ID: {user_id}, 内容: {content}")

        send, target_id = self._send_switch(data)

        ask_message: str = content[0]['data']['text']
        if ask_message.endswith(" "):
            response = self._AI_AGENT.chat(ask_message)
            send_target_message = response
        elif '报考' in ask_message:
            send_target_message = self._process_apps_content(ask_message)
        elif 'help' in ask_message:
            send_target_message = """
# 🤖 目前支持以下对话方式(支持上下文10行)：
# 🌐 DeepSeek 在线 API
# 🏠 Ollama 本地模型
# 🤖 宁夏事业编，公务员实时数据查询
#  发送 报考宁夏事业编@【岗位id】
#  发送 报考宁夏公务员@【岗位id】*（停用）
# 💬 使用方法：
# 1.添加机器人（354524747）
# 2.私聊，触发模型关键字【空格】，message+【空格】
# 例：你好啊[空格]
# 3.发送【clear】，清空上下文记录，重新开始对话
# ✨ 快来和我聊天吧！
# 管理员Q:705301804
                """
        elif 'clear' in ask_message:
            send_target_message = "上下文记录已经清空，开始新的交流吧"
        else:
            send_target_message = "发送[help]获取帮助\n管理员Q:705301804"

        send(target_id, send_target_message)

    def _meta_event_event_process(self, data):
        meta_event_type = data.get("meta_event_type")
        if meta_event_type == 'heartbeat':
            if data.get("status").get('online'):
                pass
            else:
                print(1)
        elif meta_event_type == 'lifecycle':
            # '进入元素周期检测'
            pass
        else:
            raise '未处理的元事件'

    def on_message(self, ws, message):
        data = json.loads(message)
        Event = {
            'message': '消息事件',
            'notice': '通知事件',
            'request': '请求事件',
            'meta_event': '元事件',
        }
        post_type = data.get("post_type")
        post_type = Event[post_type]
        # 根据消息类型进行处理
        if post_type == "消息事件":
            print(f"{post_type} 收到消息:", data)
            self._message_event_process(data)
        elif post_type == "通知事件":
            print(f"{post_type} 收到消息:", data)
            pass
        elif post_type == "请求事件":
            print(f"{post_type} 收到消息:", data)
            pass
        elif post_type == '元事件':
            self._meta_event_event_process(data)
        else:
            raise f'出现了其他事件请检查，{message}'

    def send_message(self, target_qq, message):
        self._ws_client.ws.send(json.dumps({
            "action": "send_msg",
            "params": {
                "user_id": target_qq,
                "message": message
            }
        }))

    def send_group_msg(self, target_group_id, message):
        self._ws_client.ws.send(json.dumps({
            "action": "send_group_msg",
            "params": {
                "group_id": target_group_id,  # 对方 QQ 号
                "message": message,
                "auto_escape": False  # 消息内容是否作为纯文本发送（即不解析 CQ 码），只在 message 字段是字符串时有效
            }
        }))

    def get_friend_list(self):
        response = self._ws_client.ws.send(json.dumps({
            "action": "get_friend_list",
        }))
        print(response)
        return response

    def other(self):
        # 懒得封装了， 够我用了
        pass
